package com.ice.controller;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ice.common.IceConstants;
import com.ice.common.IceLog;
import com.ice.common.IceProperties;
import com.ice.service.UserService;
import com.ice.service.WeChatService;
import com.sun.prism.Image;


@Controller
public class UserController {
	Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private WeChatService WeChatService ;
	
	@Autowired
	private UserService userService;
	/**
	 * 用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE
	 * 户禁止授权，则重定向后不会带上code参数，仅会带上state参数redirect_uri?state=STATE
	 * 跳转到注册页面
	 * @return
	 */
	@RequestMapping(value="/register")
	public String toRegisterPage(HttpServletRequest request, HttpServletResponse response){
		long startTime = System.currentTimeMillis();
	
		//获取code 
		String code = request.getParameter("code");
		//通过code换取网页授权access_token
		//获取code后，请求以下链接获取access_token： 
		//https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code
		
		String appid = IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI, IceConstants.WECHAT_APP_ID);
		String secret = IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI, IceConstants.WECHAT_APPSECRET);
		//拼接网页授权地址
		String webAuthorAccessTokenURL = String.format(IceConstants.WECHAT_ACCESS_TOKEN_WEB_AUTHOR_URL,appid,secret,code);
		String oepnId =WeChatService.getOpenId(code);//获取用户唯一表示openid
		request.getSession().setAttribute("openid", oepnId);//openid放到session中
		log.debug(IceLog.printLog(startTime, "跳转到报名页面", "获取的code为:"+code+"获取到的openid为"+oepnId+""));
		return "register";
	}
	
	
	
	
	/**
	 * 报名成功后，将所有信息返回界面
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/enroll",method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String enroll(HttpServletRequest request,HttpServletResponse response,@RequestParam MultipartFile[] liftImage) {
		long startTime = System.currentTimeMillis();
		String image_url= null;
		
		for (MultipartFile image : liftImage) {
			String name=null;
			if(image.isEmpty()){
				log.debug("{}",IceLog.printLog(startTime, "上传生活照片", "没有上传照片，为空"));
			}else{
				long size = image.getSize();
				 name = image.getName();
				log.debug("{}",IceLog.printLog(startTime, "上传生活照片", "成功上传照片",size,name));
			}
			String realPath ="/ice_web/images/upload/";
			try {
				FileUtils.copyInputStreamToFile(image.getInputStream(), new File(realPath, image.getOriginalFilename()));
				image_url=realPath+image.getOriginalFilename();
				
				log.debug("{}",IceLog.printLog(startTime, "上传生活照片", "照片路径为"+realPath+image.getOriginalFilename()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	

		//获取用户信息
		String activeid = request.getParameter("activeid").trim();
		String openid   = request.getParameter("openid").trim();
		System.out.println("openid"+openid);
		String name     = request.getParameter("name").trim();
		String telphone = request.getParameter("telphone").trim();
		String sex      = request.getParameter("sex").trim();
		System.err.println("性别"+sex);
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("activeid", activeid);
		map.put("openid", openid);
		map.put("sex",sex);
		map.put("name",name);
		map.put("telphone", telphone);
		map.put("image_url", image_url);

		if(userService.enroll(map)){
			log.debug(IceLog.printLog(startTime, "报名操作：方法地址：UserController.enroll", "报名成功"));
			map.put("errorcode",0);
		}else{
			log.debug(IceLog.printLog(startTime, "报名操作：方法地址：UserController.enroll", "报名失败"));
			map.put("errorcode",500);
			map.put("errormsg", "您已经参加了该比赛");
		}
		
		ObjectMapper objectMapper = new ObjectMapper();
		String returnMsg = null;
		try {
			returnMsg = objectMapper.writeValueAsString(map);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return returnMsg;
	}
}
